package com.nativetalk.service.four.member;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.TdNtPayActivity;
import com.nativetalk.bean.comment.TdNtCommentList;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberBindInfo;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.recording.TdNtMembRecordingList;
import com.nativetalk.bean.study.TdNtStudyTeachDetail;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidStudentGetui;
import com.nativetalk.common.getui.IosStudentGetui;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangzheng on 2017/3/9.
 */
@Service
public class FourMemberServiceImpl implements FourMemberService {
    private static Logger logger = Logger.getLogger(FourMemberServiceImpl.class);
    @Resource
    TdNtCourseInstanceRecordingDao tdNtCourseInstanceRecordingDao;
    @Resource
    TdNtCommentDao tdNtCommentDao;
    @Resource
    TdNtStudyTeachDao tdNtStudyTeachDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;

    @Override
    public RetInfo findRecordingByMembId(int memb_id, int currentPage, int pageSize) {
        String logInfo = this.getClass().getName() + ":findRecordingByMembId:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            int totalPage;//总页数
            int totalRecord = tdNtCourseInstanceRecordingDao.findTdNtMembRecordingSize(memb_id);//总条数
            if (totalRecord % pageSize == 0) {
                totalPage = totalRecord / pageSize;
            } else {
                totalPage = (totalRecord / pageSize) + 1;
            }
            if (currentPage >= totalPage) {
                currentPage = totalPage;
            }
            if (currentPage <= 1) {
                currentPage = 1;
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("memb_id", memb_id);
            map.put("currentPage", (currentPage - 1) * 10);
            map.put("pageSize", pageSize);

            List<TdNtMembRecordingList> recordingLists = tdNtCourseInstanceRecordingDao.findTdNtMembRecordingPage(map);
            if (recordingLists == null || recordingLists.size() <= 0) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("上课录音列表为空");
            }
            for (int i = 0; i < recordingLists.size(); i++) {
                TdNtMembRecordingList recordingList = recordingLists.get(i);
                TdNtCommentList tdNtCommentList = tdNtCommentDao.findTdNtCommentBySttId(recordingList.getStt_id());
                //用户未评价
                if (null == tdNtCommentList) {
                    recordingList.setComment_type(2);//用户未评论
                } else {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("recording_url", recordingList.getRecording_url());
                    map1.put("stt_id", recordingList.getStt_id());
                    //更新评论里的录音地址
                    tdNtCommentDao.updateCommentRecordUrl(map1);
                    if (1 == tdNtCommentList.getState()) {
                        recordingList.setComment_type(1);//已在评价页显示
                    }
                }
                TdNtStudyTeachDetail tdNtStudyTeachDetail = tdNtStudyTeachDao.findCouTeaInfoBySttId(recordingList.getStt_id());
                if (tdNtStudyTeachDetail != null) {
                    recordingList.setTea_name(tdNtStudyTeachDetail.getTea_name());
                    recordingList.setTea_head_portrait(tdNtStudyTeachDetail.getTea_head_portrait());
                    recordingList.setCou_name(tdNtStudyTeachDetail.getCou_name());
                    recordingList.setStart_time(tdNtStudyTeachDetail.getStart_time());
                } else {
                    TdNtStudyTeachDetail tdNtStudyTeachDetail2 = tdNtStudyTeachDao.findCouTeaInfoByRoomId(recordingList.getRoom_id());
                    if (tdNtStudyTeachDetail2 != null) {
                        recordingList.setTea_name(tdNtStudyTeachDetail2.getTea_name());
                        recordingList.setTea_head_portrait(tdNtStudyTeachDetail2.getTea_head_portrait());
                        recordingList.setCou_name(tdNtStudyTeachDetail2.getCou_name());
                        recordingList.setStart_time(tdNtStudyTeachDetail2.getStart_time());
                    } else {
                        logger.error("无效的课程for stt_id:" + recordingList.getStt_id());
                    }
                }


            }

            Map<String, Object> result = new HashMap<>();
            result.put("recordingLists", recordingLists);
            result.put("totalPage", totalPage);
            result.put("totalRecord", totalRecord);
            result.put("currentPage", currentPage);
            retInfo.setObj(result);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取上课录音列表成功");

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateRecordingByMembId(int stt_id, String state) {
        String logInfo = this.getClass().getName() + ":updateRecordingByMembId:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("stt_id", stt_id);
            //在课程页显示
            if ("1".equals(state)) {
                map.put("state", 1);
                tdNtCourseInstanceRecordingDao.updateTdNtMembCommentRecording(map);
            }
            //删除
            else if ("2".equals(state)) {
                map.put("type", 0);
                tdNtCourseInstanceRecordingDao.updateTdNtMembRecording(map);
            }
            Map<String, Object> result = new HashMap<>();

            retInfo.setObj(result);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("更新用户上课录音状态成功");

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateMemberBalance(TdNtMember tdNtMember, BigDecimal amount, String orderNo) {
        String logInfo = this.getClass().getName() + ":updateMemberBalance:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            int flag = 0;
            BigDecimal give_amount = BigDecimal.valueOf(0);
            List<TdNtPayActivity> tdNtPayActivity = (List<TdNtPayActivity>) MemcachedUtils.get("TdNtPayActivityIndex");
            for (int i = 0; i < tdNtPayActivity.size(); i++) {
                if (amount.intValue() >= tdNtPayActivity.get(i).getRecharge_amount().intValue()) {
                    if (flag < tdNtPayActivity.get(i).getRecharge_amount().intValue()) {
                        give_amount = tdNtPayActivity.get(i).getGive_amount();
                        flag = tdNtPayActivity.get(i).getRecharge_amount().intValue();
                    }
                }
            }

            BigDecimal total_amount; //充值的总价格
            //获取用户余额
            BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());

            TdNtMembFoundChangeInset tdNtMembFoundChangeInset;

            /**
             * 检验订单号
             */
            if (null == orderNo || "".equals(orderNo.trim())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("传入的订单号为null或空");
                return retInfo;
            }
            tdNtMembFoundChangeInset = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);

            //符合满几送几的最低价格
            String change_name;
            if (flag != 0) {
                total_amount = amount.add(give_amount);
                change_name = "满" + flag + "送" + give_amount;
            } else {
                total_amount = amount;
                change_name = "充值";
            }

            /**
             * notify异步先返回，该订单的记录已插入数据库
             */
            if (null != tdNtMembFoundChangeInset) {
                logger.info("notify异步先返回，该订单的记录已插入数据库");
                //补全账户余额资金的订单信息
                tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_in);
                tdNtMembFoundChangeInset.setType(Constants.ChargeType.recharge_code);
                tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance);
                tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance.add(total_amount));
                tdNtMembFoundChangeInset.setMoney_change_type(Constants.PaymentChannel.wallet);
                tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChangeInset);

                if (Constants.PayState.success.equals(tdNtMembFoundChangeInset.getState())) {
                    //更新用户余额
                    TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                    tdNtMemberInvite.setMemb_balance(memb_balance.add(total_amount));
                    tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);

                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("充值成功");
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("充值失败");
                }
            } else {
                tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                //添加一条资金变动记录
                tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                tdNtMembFoundChangeInset.setMfchg_change_amount(total_amount);
                tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_in);
                tdNtMembFoundChangeInset.setState(Constants.PayState.success);//1 支付未完成，2 支付已完成
                tdNtMembFoundChangeInset.setType(Constants.ChargeType.recharge_code);
                tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance);
                tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance.add(total_amount));
                tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);

                //更新用户余额
                TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                tdNtMemberInvite.setMemb_balance(memb_balance.add(total_amount));
                tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());
                tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("充值成功");
            }


            /**
             * 支付成功后发送消息给学生端
             */
            if (tdNtMember != null) {
                if (tdNtMember.getEqu_client_id() != null && !(tdNtMember.getEqu_client_id().equals("1212313fasdf"))) {
                    if (tdNtMember.getEqu_type().equals("1")) {
                        AndroidStudentGetui.pay("外教君", "充值成功", tdNtMember.getEqu_client_id());
                    } else {
                        IosStudentGetui.pay("外教君", "充值成功", tdNtMember.getEqu_client_id());

                    }

                }
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }

        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findMemberBindStatus(TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":findMemberBindStatus:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMemberBindInfo tdNtMemberBindInfo = tdNtMemberDao.findMemberBindStatusByMembId(tdNtMember.getMemb_id());
            if (null != tdNtMemberBindInfo.getMemb_phone() && tdNtMemberBindInfo.getMemb_phone().trim().length() > 0) {
                tdNtMemberBindInfo.setPhone_isBunding(Constants.MemberBindStatus.Binded);
            }
            if (null != tdNtMemberBindInfo.getWx_num() && tdNtMemberBindInfo.getWx_num().trim().length() > 0) {
                tdNtMemberBindInfo.setWx_isBunding(Constants.MemberBindStatus.Binded);
            }
            if (null != tdNtMemberBindInfo.getQq_num() && tdNtMemberBindInfo.getQq_num().trim().length() > 0) {
                tdNtMemberBindInfo.setQq_isBunding(Constants.MemberBindStatus.Binded);
            }
            if (null != tdNtMemberBindInfo.getSinaWeibo_num() && tdNtMemberBindInfo.getSinaWeibo_num().trim().length() > 0) {
                tdNtMemberBindInfo.setSinaWeibo_isBunding(Constants.MemberBindStatus.Binded);
            }
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取用户绑定信息成功");
            retInfo.setObj(tdNtMemberBindInfo);

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo memberBindThirdParty(TdNtMember tdNtMember, String thirdParty_type, String third_token) {
        String logInfo = this.getClass().getName() + ":memberBindThirdParty:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMember memberRegister = tdNtMemberDao.findTdNtMemberByLoginTypeAndThirdToken(third_token, Integer.valueOf(thirdParty_type));
            if (null != memberRegister) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("该第三方账号已被绑定");
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("memb_id", tdNtMember.getMemb_id());
                map.put("thirdParty_type", thirdParty_type);
                map.put("third_token", third_token);
                tdNtMemberDao.updateMemberThirdPartyBindStatus(map);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("用户绑定第三方账号成功");

            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo memberUnBindThirdParty(TdNtMember tdNtMember, String thirdParty_type) {
        String logInfo = this.getClass().getName() + ":memberBindThirdParty:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("memb_id", tdNtMember.getMemb_id());
            map.put("thirdParty_type", thirdParty_type);
            map.put("third_token", null);
            tdNtMemberDao.updateMemberThirdPartyBindStatus(map);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("用户解绑第三方账号成功");

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
